//
//  DynamicView.m
//  AoJi
//
//  Created by IMacLife on 15/1/30.
//  Copyright (c) 2015年 xuanheng. All rights reserved.
//
//我的动态

#import "DynamicView.h"
#import "Color.h"
#import "UIImageView+WebCache.h"
#import "YHNetwork.h"

@implementation DynamicView

-(instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self loadView];
        [self loadData];
    }
    return self;
}

//加载view
-(void)loadView
{
    _tableview = [[UITableView alloc]initWithFrame:self.bounds style:UITableViewStylePlain];
    _tableview.delegate=self;
    _tableview.dataSource=self;
    _tableview.backgroundColor=[UIColor clearColor];
    //隐藏分割线
    _tableview.separatorStyle=UITableViewCellAccessoryNone;
    [self addSubview:_tableview];
    
    UIView *footView = [[UIView alloc]init];
    footView.backgroundColor=[Color colorFromHexRGB:@"e4e4e4"];
    _tableview.tableFooterView=footView;
}

-(void)loadData
{
    //http://cent.dsgrd.com/me/river   分页 拿到最后一条的id再传一次(时间下面的id)
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"firstid"] = @"0";
    params[@"lastid"] = @"9";
    params[@"limit"] = @"10";
    
    NSLog(@"%@",[kUserDefaults objectForKey:kAccessToken]);
    [YHNetwork getInformationWithReguestType:RequestTypePost WithParameters:params WithApi:@"me/river" WhenSuccess:^(NSMutableDictionary *response) {
        NSLog(@"%@",response);
        dataArray=[NSMutableArray arrayWithArray:response]; //转为可变数组方便删除
        [_tableview reloadData];
        
    } WhenFailure:^(NSError *failure) {
        NSLog(@"%@",failure);
    }];
}

#pragma mark ----------------UITableViewDelegate
//一个分区显示多少行
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return dataArray.count;
}


//UITableViewCell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"cell";
    UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    [cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    cell.backgroundColor = [UIColor clearColor];
    //cell选中样式
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    dict = dataArray[indexPath.row];
    NSDictionary *notifierDict = dict[@"notifier"];
    objDic = dict[@"object"];
    dataDic =dict[@"object_ext_data"];
    if ([dict[@"action"] isEqualToString:@"enter"]) {
        [self loadEnterMessage:cell.contentView];
    }else if([dict[@"action"] isEqualToString:@"booking"]){
        [self loadBookingMessage:cell.contentView];
    }else if ([dict[@"action"] isEqualToString:@"talk"]){
        [self loadTalkMessage:cell.contentView];
    }
    
    return cell;
}


//cell行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *tempDict = dataArray[indexPath.row];
    if ([tempDict[@"action"] isEqualToString:@"enter"]) {
        NSString *text = @"我刚报名了一个";
        NSString *name = tempDict[@"object"][@"title"];
        NSString *desc = tempDict[@"object_ext_data"][@"title"];
        NSString *sysStr =[NSString stringWithFormat:@"%@ %@ “%@”",text,name,desc];
        return  [self getCellHeightByContent:sysStr];
    }else if([tempDict[@"action"] isEqualToString:@"booking"]){
        NSString *userStr = tempDict[@"object"][@"username"];
        NSString *str= @"预约了我";
        return [self getCellHeightByContent:[NSString stringWithFormat:@"“%@” %@",userStr,str]];
    }else if ([tempDict[@"action"] isEqualToString:@"talk"]){
        return [self getCellHeightByContent:tempDict[@"object"][@"body"]];
    }
    return 0;
}


//cell  ------  select
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //根据id去请求url
    NSDictionary *dic = dataArray[indexPath.row];
    if ([dic[@"action"] isEqualToString:@"enter"]) {
        MessageViewController *messageVC = [[MessageViewController alloc]init];
        messageVC.objType = [NSString stringWithFormat:@"%@",dic[@"object_type"]];
        messageVC.objid = [NSString stringWithFormat:@"%@",dic[@"object_id"]];
        
        [self.viewController.navigationController pushViewController:messageVC animated:YES];
    }else if([dic[@"action"] isEqualToString:@"booking"]){
        
    }else if ([dic[@"action"] isEqualToString:@"talk"]){
        btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame=CGRectMake(0, 0, self.window.frame.size.width, self.window.frame.size.height);
        btn.backgroundColor=[UIColor blackColor];
        btn.alpha=0.5;
        [btn addTarget:self action:@selector(removeChat) forControlEvents:UIControlEventTouchUpInside];
        [self.window addSubview:btn];
        
        if (chatView) {
            [[NSNotificationCenter defaultCenter]removeObserver:chatView];
        }
        
        chatView = [[ChatView alloc]initWithFrame:CGRectMake(20, 64, Mainwidth-40, MainHeight-104)];
        
        chatView.userID=[NSString stringWithFormat:@"%@",dic[@"notifier"][@"id"]];
        chatView._id=[NSString stringWithFormat:@"%@",dic[@"id"]];
        chatView.backgroundColor=[UIColor whiteColor];
        chatView.layer.cornerRadius=5;
        [chatView loadData];
        [self.window addSubview:chatView];
    }
   
}

#pragma mark   -------- 聊天
//收起聊天框
-(void)removeChat
{
    [btn removeFromSuperview];
    [chatView removeFromSuperview];
}

//设置tableView能编辑
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

//提交删除
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        
        NSDictionary *delete = dataArray[indexPath.row];
        
        NSString *deleteStr = [NSString stringWithFormat:@"me/river/remove?id=%@",delete[@"id"]];
        [YHNetwork getInformationWithReguestType:RequestTypePost WithParameters:nil WithApi:deleteStr WhenSuccess:^(NSMutableDictionary *response) {
            NSLog(@"%@",response);
            NSMutableDictionary *deleteDict = response;
            int i = [deleteDict[@"code"]intValue];
            if (i == 0) {
                [dataArray removeObjectAtIndex:indexPath.row];
                [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationTop];
            }else{
                UIAlertView *fail = [[UIAlertView alloc]initWithTitle:@"提示" message:@"删除失败,请稍后重试" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            }
            
        } WhenFailure:^(NSError *failure) {
            NSLog(@"%@",failure);
        }];
    }
    
}

//设置删除按钮的标题
-(NSString*)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

#pragma mark - -----------根据消息类型加载消息列表
- (void)loadEnterMessage:(UIView*)superView{
    NSInteger notifireid = [NSString stringWithFormat:@"%@",dict[@"notifier_id"]].integerValue;
    UIImageView *userImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"xitonftouxiang"]];
    //userImg.image= notifireid == 0 ?[UIImage imageNamed:@"xitonftouxiang"]:objDic[@"avatar"];
    userImg.frame=CGRectMake(5, 5, 35, 35);
    userImg.backgroundColor=[UIColor clearColor];
    [superView addSubview:userImg];
    
    UILabel *systemLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(userImg.frame)+5, 13, 100, 20)];
    systemLabel.text = notifireid ==0 ? @"系统消息":@"对话消息";
    systemLabel.backgroundColor=[UIColor clearColor];
    [superView addSubview:systemLabel];
    
    UIView *msgBox = [self messageBox];
    UILabel *message = [[UILabel alloc]initWithFrame:CGRectMake(5, 5, msgBox.frame.size.width-10, 0)];
    
    NSString *text = @"我刚报名了一个";
    NSString *name = dataDic[@"title"];
    NSString *desc = objDic[@"title"];
    NSString *sysStr =[NSString stringWithFormat:@"%@ %@ “%@”",text,name,desc];
    message.text =sysStr;
    message.numberOfLines=0;
    message.lineBreakMode=UILineBreakModeCharacterWrap;
    message.font = [UIFont systemFontOfSize:13];
    
    //设置文字颜色
    if (notifireid == 0) {
        NSMutableAttributedString *attributed = [[NSMutableAttributedString alloc] initWithString:message.text];
        [attributed addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(text.length + name.length + 1, desc.length+2)];
        [message setAttributedText:attributed];
    }
    [message sizeToFit];
    
    [msgBox addSubview:message];
    
    UILabel *timeLab = [self timeLabel:msgBox y:CGRectGetMaxY(message.frame)+10];
    msgBox.frame = CGRectMake(msgBox.frame.origin.x, msgBox.frame.origin.y, msgBox.frame.size.width, CGRectGetMaxY(timeLab.frame));
    [msgBox addSubview:timeLab];
    [superView addSubview:msgBox];
}

- (void)loadTalkMessage:(UIView*)superView{
    UIImageView *userImg = [[UIImageView alloc]initWithFrame:CGRectMake(5, 5, 35, 35)];
    userImg.layer.cornerRadius = userImg.frame.size.width/2;
    userImg.layer.masksToBounds = YES;
    //头像地址不为空，读取url图片
    if (dict[@"object"][@"avatar"]) {
      [userImg sd_setImageWithURL:[NSURL URLWithString:dict[@"object"][@"avatar"]] placeholderImage:[UIImage imageNamed:@"morentouxiang"]];
    }else{
        userImg.image = [UIImage imageNamed:@"morentouxiang"];
    }
    [superView addSubview:userImg];
    
    //用户名
    UILabel *userName = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(userImg.frame)+5, 13, 0, 0)];
    userName.text=dict[@"notifier"][@"username"];
    userName.backgroundColor=[UIColor clearColor];
    userName.numberOfLines = 1;
    [userName sizeToFit];
    [superView addSubview:userName];
    
    //消息
    UIView *msgBox = [self messageBox];
    UILabel *message = [[UILabel alloc]initWithFrame:CGRectMake(5, 5, msgBox.frame.size.width-10, 0)];
    message.text = dict[@"object"][@"body"];
    message.numberOfLines=0;
    message.font = [UIFont systemFontOfSize:12];
    [message sizeToFit];
    [msgBox addSubview:message];
    
    UILabel *timeLab = [self timeLabel:msgBox y:CGRectGetMaxY(message.frame)+10];
    msgBox.frame = CGRectMake(msgBox.frame.origin.x, msgBox.frame.origin.y, msgBox.frame.size.width, CGRectGetMaxY(timeLab.frame));
    [msgBox addSubview:timeLab];
    [superView addSubview:msgBox];
}

- (void)loadBookingMessage:(UIView*)superView{
    UIImageView *userImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"xitonftouxiang"]];
    userImg.frame=CGRectMake(5, 5, 35, 35);
    userImg.backgroundColor=[UIColor clearColor];
    [superView addSubview:userImg];
    
    UILabel *systemLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(userImg.frame)+5, 13, 100, 20)];
    systemLabel.text=@"系统消息";
    systemLabel.backgroundColor=[UIColor clearColor];
    [superView addSubview:systemLabel];
    
    UIView *msgBox = [self messageBox];
    
    UILabel *message = [[UILabel alloc]initWithFrame:CGRectMake(5, 5, msgBox.frame.size.width-10, 30)];
    NSString *userStr = dict[@"object"][@"username"];
    NSString *str= @"预约了我";
    message.text = [NSString stringWithFormat:@"“%@” %@",userStr,str];
    message.numberOfLines=0;
    message.font = [UIFont systemFontOfSize:12];
    
    NSMutableAttributedString *attributed = [[NSMutableAttributedString alloc] initWithString:message.text];
    [attributed addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, userStr.length+2)];
    [message setAttributedText:attributed];
    [message sizeToFit];
    [msgBox addSubview:message];

    UILabel *timeLab = [self timeLabel:msgBox y:CGRectGetMaxY(message.frame)+10];
    msgBox.frame = CGRectMake(msgBox.frame.origin.x, msgBox.frame.origin.y, msgBox.frame.size.width, CGRectGetMaxY(timeLab.frame));
    [msgBox addSubview:timeLab];
    [superView addSubview:msgBox];
}

/**
 *  消息盒子
 */
- (UIView*)messageBox{
    UIView *box = [[UIView alloc] initWithFrame:CGRectMake(50, 45, Mainwidth - 60, 0)];
    box.backgroundColor=[UIColor whiteColor];
    //圆角
    box.layer.cornerRadius = 3;
    box.layer.masksToBounds = YES;
    return box;
}

/**
 *  日期
 *
 *  @param superView 父视图
 *  @param y         y轴值
 *
 *  @return 返回日期label
 */
- (UILabel*)timeLabel:(UIView*)superView y:(CGFloat)y{
    UILabel *timeLab=[[UILabel alloc]initWithFrame:CGRectMake(0, y, 0, 0)];
    NSString *time = dict[@"created_at"];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm"];
    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:(NSTimeInterval)[time intValue]];
    time=[formatter stringFromDate:confromTimesp];
    timeLab.text=time;
    timeLab.font=[UIFont systemFontOfSize:12];
    [timeLab sizeToFit];
    timeLab.frame = CGRectMake(superView.frame.size.width - timeLab.frame.size.width - 10, timeLab.frame.origin.y, timeLab.frame.size.width, timeLab.frame.size.height);
    return timeLab;
}

/**
 *  根据消息内容计算cell高度(内容y轴+内容高度+内容与时间的空隙+时间高度+cell与cell之间的空隙)
 *
 *  @param content 消息内容
 *
 *  @return 返回cell高度
 */
- (CGFloat)getCellHeightByContent:(NSString*)content{
    CGFloat cellHeight = 0;
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, Mainwidth - 80, 0)];
    label.text = content;
    label.numberOfLines = 0;
    label.font = [UIFont systemFontOfSize:12];
    [label sizeToFit];
    
    cellHeight = 50 + label.frame.size.height + 10 + 12 + 10;
    label = nil;
    return cellHeight;
}

@end
